package com.i_art_engineer.meigong.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.i_art_engineer.meigong.AppConsts;
import com.i_art_engineer.meigong.AppHttpClient;
import com.i_art_engineer.meigong.R;
import com.i_art_engineer.meigong.base.ActionBarActivity;
import com.i_art_engineer.meigong.util.DimenUtils;
import com.i_art_engineer.meigong.widget.LoadingAndRetryManager;
import com.i_art_engineer.meigong.widget.OnLoadingAndRetryListener;
import com.i_art_engineer.meigong.widget.SimpleSectionedGridAdapter;
import com.i_art_engineer.meigong.widget.SimpleSectionedGridAdapter.Section;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import cz.msebera.android.httpclient.Header;

/**
 * 作品欣赏界面
 */
public class WorksActivity extends ActionBarActivity {

    //底部
    public View.OnClickListener listener1 = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            switch (v.getId()) {

                case R.id.ll_btn_works:
//                    intent.setClassName(WorksActivity.this,)；
//                    Toast.makeText(WorksActivity.this, "点击了！不用跳转", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.ll_btn_pic:
                    intent.setClass(WorksActivity.this, PhotoSelectorActivity.class);
                    startActivity(intent);
                    break;
                case R.id.ll_btn_personal:
                    intent.setClass(WorksActivity.this, AccountActivity.class);
                    startActivity(intent);
                    break;

            }

        }
    };

    private GridView grid;
    private ImageAdapter mAdapter;
    private ArrayList<Section> mSections = new ArrayList<>();
    private ArrayList<String> mPhotos = new ArrayList<>();
    private String groupId = null;
    private Bitmap mMoreBmp;
    private LinearLayout ll_btn_works, ll_tab, ll_btn_pic, ll_btn_personal;

    public View.OnClickListener listener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String id = (String) v.getTag();
            Intent intent = new Intent(WorksActivity.this, WorksActivity.class);
            intent.putExtra("group_id", id);
            startActivity(intent);

        }

    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_works);

        initActionBar(R.string.title_works);
        Intent intent = getIntent();
        groupId = intent.getStringExtra("group_id");
        grid = (GridView) findViewById(R.id.works_sticky_grid);
        mMoreBmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.more);

        ll_tab = (LinearLayout) findViewById(R.id.ll_tab);
        ll_btn_works = (LinearLayout) ll_tab.findViewById(R.id.ll_btn_works);
        ll_btn_works.setOnClickListener(listener1);
        ll_btn_pic = (LinearLayout) ll_tab.findViewById(R.id.ll_btn_pic);
        ll_btn_pic.setOnClickListener(listener1);
        ll_btn_personal = (LinearLayout) ll_tab.findViewById(R.id.ll_btn_personal);
        ll_btn_personal.setOnClickListener(listener1);

        refreashData();
    }

    private boolean isSingleGroupMode() {
        return this.groupId != null;
    }

    /**
     * 成功则返回所属分组的ID，否则返回NULL;
     *
     * @param position
     * @return
     */
    public String isLastSectionImage(int position) {
        if (position + 1 == mPhotos.size())
            return (String) mSections.get(mSections.size() - 1).getTag();

        if (mSections.size() > 1) {
            for (int i = 1; i < mSections.size(); i++) {
                Section section = mSections.get(i);
                int indx = section.getPosition();
                if (indx != 0 && indx == position + 1) {
                    return (String) mSections.get(i - 1).getTag();
                }
            }
        }
        return null;
    }

    /**
     * 刷新数据
     */
    private void refreashData() {
        AsyncHttpResponseHandler jhandler = new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {
                    Log.i("c", response.toString());
                    int code = response.getInt("code");
                    String msg = response.getString("msg");
                    Log.i("Works-msg", msg);
                    int indx = 0;
                    if (code == 200) {
                        JSONArray imageArr = response.getJSONArray("data");
                        mSections.clear();
                        mPhotos.clear();
                        for (int i = 0; i < imageArr.length(); i++) {
                            JSONObject objGroup = imageArr.getJSONObject(i);
                            if (isSingleGroupMode()) {
                                String url = objGroup.getString("img_url");
                                mPhotos.add(url);
                            } else {
                                String name = objGroup.getString("title");
                                String id = objGroup.getString("id");
                                Section section = new Section(indx, name);
                                section.setTag(id);
                                JSONArray items = objGroup.getJSONArray("items");
                                if (items.length() > 0) {
                                    for (int j = 0; j < items.length(); j++) {
                                        JSONObject item = items.getJSONObject(j);
                                        mPhotos.add(item.getString("img_url"));
                                    }
                                    mSections.add(section);
                                    indx += items.length();
                                }
                            }
                        }
                        mAdapter = new ImageAdapter(WorksActivity.this);
                        SimpleSectionedGridAdapter simpleSectionedGridAdapter = new SimpleSectionedGridAdapter(
                                WorksActivity.this, mAdapter,
                                R.layout.works_grid_item_header, R.id.header_layout, R.id.header);
                        simpleSectionedGridAdapter.setGridView(grid);
                        if (!isSingleGroupMode()) {
                            simpleSectionedGridAdapter.setSections(mSections.toArray(new Section[0]));
                        }
                        grid.setAdapter(simpleSectionedGridAdapter);
                    }
                } catch (JSONException e) {
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.i("imageArr", responseString);
            }
        };
        if (isSingleGroupMode()) {
            RequestParams params = new RequestParams();
            params.add("id", groupId);
            AppHttpClient.post(AppConsts.API_WORKS_CAT, params, jhandler);
        } else
            AppHttpClient.post(AppConsts.API_WORKS_GET, jhandler);
    }

    public class ImageAdapter extends BaseAdapter {

        private LayoutInflater mInflater;

        public ImageAdapter(Context context) {
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return mPhotos.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ImageView image;
            final int itemIndx = position;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.works_grid_item, parent, false);
            }
            image = ViewHolder.get(convertView, R.id.image);
            image.setPadding(2, 2, 2, 2);
            image.setBackgroundDrawable(WorksActivity.this.getResources().getDrawable(R.drawable.works_item_bg));
            Picasso.with(WorksActivity.this)
                    .load(mPhotos.get(position)).placeholder(R.drawable.empty_photo)
                    .memoryPolicy(MemoryPolicy.NO_STORE)
                    .into(new Target() {
                        @Override
                        public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
                            if (isSingleGroupMode()) {
                                image.setImageBitmap(bitmap);
                                //图片预览
                                image.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent intent = new Intent(WorksActivity.this, SingleImageActivity.class);
                                        intent.putExtra("image", mPhotos.get(position));
                                        startActivity(intent);
                                    }
                                });
                            } else {
                                String id = WorksActivity.this.isLastSectionImage(itemIndx);
                                if (id != null) {
                                    image.setImageBitmap(addWatermark(bitmap, mMoreBmp));
                                    image.setOnClickListener(listener);
                                    image.setTag(id);
                                } else {
                                    image.setImageBitmap(bitmap);
                                    //图片预览
                                    image.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            Intent intent=new Intent(WorksActivity.this,SingleImageActivity.class);
                                            intent.putExtra("image",mPhotos.get(position));
                                            startActivity(intent);
                                        }
                                    });
                                }
                            }
                        }

                        @Override
                        public void onBitmapFailed(final Drawable errorDrawable) {
                        }

                        @Override
                        public void onPrepareLoad(final Drawable placeHolderDrawable) {
                        }

                        private Bitmap addWatermark(Bitmap src, Bitmap watermark) {
                            if (src == null || watermark == null) {
                                Log.d("Works_watermark", "src is null");
                                return src;
                            }

                            int sWid = src.getWidth();
                            int sHei = src.getHeight();
                            int wWid = watermark.getWidth();
                            int wHei = watermark.getHeight();
                            if (sWid == 0 || sHei == 0) {
                                return null;
                            }

                            if (sWid < wWid || sHei < wHei) {
                                return src;
                            }

                            Bitmap bitmap = Bitmap.createBitmap(sWid, sHei, Bitmap.Config.ARGB_8888);
                            try {
                                Canvas cv = new Canvas(bitmap);
                                Paint paint = new Paint();
                                ColorMatrix colorMatrix = new ColorMatrix();
                                colorMatrix.setSaturation(0);
                                ColorMatrixColorFilter colorMatrixFilter = new ColorMatrixColorFilter(colorMatrix);
                                paint.setColorFilter(colorMatrixFilter);
                                src = fastblur(src, 5);
                                cv.drawBitmap(src, 0, 0, paint);
                                cv.drawBitmap(watermark, (sWid - wWid) / 2, (sHei - wHei) / 2, null);
                                cv.save(Canvas.ALL_SAVE_FLAG);
                                cv.restore();
                            } catch (Exception e) {
                                bitmap = null;
                                e.getStackTrace();
                            }
                            return bitmap;
                        }

                        public Bitmap fastblur(Bitmap sentBitmap, int radius) {
                            Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);

                            if (radius < 1) {
                                return (null);
                            }

                            int w = bitmap.getWidth();
                            int h = bitmap.getHeight();

                            int[] pix = new int[w * h];
                            bitmap.getPixels(pix, 0, w, 0, 0, w, h);

                            int wm = w - 1;
                            int hm = h - 1;
                            int wh = w * h;
                            int div = radius + radius + 1;

                            int r[] = new int[wh];
                            int g[] = new int[wh];
                            int b[] = new int[wh];
                            int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
                            int vmin[] = new int[Math.max(w, h)];

                            int divsum = (div + 1) >> 1;
                            divsum *= divsum;
                            int temp = 256 * divsum;
                            int dv[] = new int[temp];
                            for (i = 0; i < temp; i++) {
                                dv[i] = (i / divsum);
                            }

                            yw = yi = 0;

                            int[][] stack = new int[div][3];
                            int stackpointer;
                            int stackstart;
                            int[] sir;
                            int rbs;
                            int r1 = radius + 1;
                            int routsum, goutsum, boutsum;
                            int rinsum, ginsum, binsum;

                            for (y = 0; y < h; y++) {
                                rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
                                for (i = -radius; i <= radius; i++) {
                                    p = pix[yi + Math.min(wm, Math.max(i, 0))];
                                    sir = stack[i + radius];
                                    sir[0] = (p & 0xff0000) >> 16;
                                    sir[1] = (p & 0x00ff00) >> 8;
                                    sir[2] = (p & 0x0000ff);
                                    rbs = r1 - Math.abs(i);
                                    rsum += sir[0] * rbs;
                                    gsum += sir[1] * rbs;
                                    bsum += sir[2] * rbs;
                                    if (i > 0) {
                                        rinsum += sir[0];
                                        ginsum += sir[1];
                                        binsum += sir[2];
                                    } else {
                                        routsum += sir[0];
                                        goutsum += sir[1];
                                        boutsum += sir[2];
                                    }
                                }
                                stackpointer = radius;

                                for (x = 0; x < w; x++) {

                                    r[yi] = dv[rsum];
                                    g[yi] = dv[gsum];
                                    b[yi] = dv[bsum];

                                    rsum -= routsum;
                                    gsum -= goutsum;
                                    bsum -= boutsum;

                                    stackstart = stackpointer - radius + div;
                                    sir = stack[stackstart % div];

                                    routsum -= sir[0];
                                    goutsum -= sir[1];
                                    boutsum -= sir[2];

                                    if (y == 0) {
                                        vmin[x] = Math.min(x + radius + 1, wm);
                                    }
                                    p = pix[yw + vmin[x]];

                                    sir[0] = (p & 0xff0000) >> 16;
                                    sir[1] = (p & 0x00ff00) >> 8;
                                    sir[2] = (p & 0x0000ff);

                                    rinsum += sir[0];
                                    ginsum += sir[1];
                                    binsum += sir[2];

                                    rsum += rinsum;
                                    gsum += ginsum;
                                    bsum += binsum;

                                    stackpointer = (stackpointer + 1) % div;
                                    sir = stack[(stackpointer) % div];

                                    routsum += sir[0];
                                    goutsum += sir[1];
                                    boutsum += sir[2];

                                    rinsum -= sir[0];
                                    ginsum -= sir[1];
                                    binsum -= sir[2];

                                    yi++;
                                }
                                yw += w;
                            }
                            for (x = 0; x < w; x++) {
                                rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
                                yp = -radius * w;
                                for (i = -radius; i <= radius; i++) {
                                    yi = Math.max(0, yp) + x;

                                    sir = stack[i + radius];

                                    sir[0] = r[yi];
                                    sir[1] = g[yi];
                                    sir[2] = b[yi];

                                    rbs = r1 - Math.abs(i);

                                    rsum += r[yi] * rbs;
                                    gsum += g[yi] * rbs;
                                    bsum += b[yi] * rbs;

                                    if (i > 0) {
                                        rinsum += sir[0];
                                        ginsum += sir[1];
                                        binsum += sir[2];
                                    } else {
                                        routsum += sir[0];
                                        goutsum += sir[1];
                                        boutsum += sir[2];
                                    }

                                    if (i < hm) {
                                        yp += w;
                                    }
                                }
                                yi = x;
                                stackpointer = radius;
                                for (y = 0; y < h; y++) {
                                    // Preserve alpha channel: ( 0xff000000 & pix[yi] )
                                    pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];

                                    rsum -= routsum;
                                    gsum -= goutsum;
                                    bsum -= boutsum;

                                    stackstart = stackpointer - radius + div;
                                    sir = stack[stackstart % div];

                                    routsum -= sir[0];
                                    goutsum -= sir[1];
                                    boutsum -= sir[2];

                                    if (x == 0) {
                                        vmin[y] = Math.min(y + r1, hm) * w;
                                    }
                                    p = x + vmin[y];

                                    sir[0] = r[p];
                                    sir[1] = g[p];
                                    sir[2] = b[p];

                                    rinsum += sir[0];
                                    ginsum += sir[1];
                                    binsum += sir[2];

                                    rsum += rinsum;
                                    gsum += ginsum;
                                    bsum += binsum;

                                    stackpointer = (stackpointer + 1) % div;
                                    sir = stack[stackpointer];

                                    routsum += sir[0];
                                    goutsum += sir[1];
                                    boutsum += sir[2];

                                    rinsum -= sir[0];
                                    ginsum -= sir[1];
                                    binsum -= sir[2];

                                    yi += w;
                                }
                            }
                            bitmap.setPixels(pix, 0, w, 0, 0, w, h);
                            return (bitmap);
                        }

                    });
            return convertView;
        }

    }


    public static class ViewHolder {

        @SuppressWarnings("unchecked")
        public static <T extends View> T get(View view, int id) {
            SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
            if (viewHolder == null) {
                viewHolder = new SparseArray<View>();
                view.setTag(viewHolder);
            }
            View childView = viewHolder.get(id);
            if (childView == null) {
                childView = view.findViewById(id);
                viewHolder.put(id, childView);
            }
            return (T) childView;
        }

    }

}
